package multdata.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.JpaVendorAdapter;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import javax.persistence.EntityManager;
import javax.sql.DataSource;

/**
 * Stimulate
 */
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(
        entityManagerFactoryRef = "entityManagerFactoryStimulate",
        transactionManagerRef = "transactionManagerStimulate",
        basePackages = {"multdata.repository.stimulate"})
public class JpaConfigStimulate {

    @Autowired
    @Qualifier("dataSourceStimulate")
    private DataSource dataSource;
    @Autowired
    JpaVendorAdapter jpaVendorAdapter;

    @Primary
    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryStimulate(EntityManagerFactoryBuilder builder) {
        LocalContainerEntityManagerFactoryBean emfb =
                builder.dataSource(dataSource).packages("multdata.entity.stimulate").build();
        emfb.setJpaVendorAdapter(jpaVendorAdapter);
        return emfb;
    }

    @Primary
    @Bean
    public EntityManager entityManagerStimulate(EntityManagerFactoryBuilder builder) {
        return entityManagerFactoryStimulate(builder).getObject().createEntityManager();
    }

    @Primary
    @Bean
    PlatformTransactionManager transactionManagerStimulate(EntityManagerFactoryBuilder builder) {
        return new JpaTransactionManager(entityManagerFactoryStimulate(builder).getObject());
    }
}
